package com.lazy.gridfs;

import java.util.Date;

import com.lazy.lib.util.DateUtil;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.GridFSUploadStream;

public class MongoMgr {

    private String mongoClientUrl;
    // only one instance 
    private MongoClient mongoClient;
    
    public MongoMgr(String mongoClientUrl){
        this.mongoClientUrl = mongoClientUrl;
    }
    
    public void init() {
        // or use a connection string
        MongoClientURI connectionString = new MongoClientURI(mongoClientUrl);
        mongoClient = new MongoClient(connectionString);
    }
    
    public void close() {
        if (mongoClient != null) {
            mongoClient.close();
            mongoClient = null;
        }
    }
    
    public MongoDatabase getDatabase(String dbName) {
        return mongoClient.getDatabase(dbName);
    }
    
    public GridFSBucket getFSBucket(String dbName) {
        return GridFSBuckets.create(getDatabase(dbName));
    }
    
    public GridFSBucket getFSBucket(MongoDatabase database) {
        return GridFSBuckets.create(database);
    }
    

    public void writeBinData(GridFSBucket gridFSBucket, byte[] binData) {

        if (binData != null && binData.length > 0) {
        long time = System.currentTimeMillis();
        String fileName = DateUtil.formatDate(new Date(time), "yyyyMMddHHmmss");
        GridFSUploadStream uploadStream = null;
        try {
            uploadStream = gridFSBucket.openUploadStream(fileName);
            gridFSBucket.openUploadStream(fileName);
            uploadStream.write(binData);
        } finally {
            if (uploadStream != null) {
                uploadStream.close();
            }
        }
        }
    }
}
